<?php

@require "config.php";
if(!$config_done) {
	// Default settings
	// DO NOT CHANGE THESE - MAKE CHANGES IN config.php INSTEAD

	$thumb_size_x=200;
	$thumb_size_y=200;
	$thumb_jpeg_quality=95;
	$thumb_filename_prefix=".tn-";
}

function resize($max_x, $max_y, $filename, $dest_fn) {
	global $thumb_jpeg_quality;
	$fd = @fopen($filename,"r");

	$image_string = fread($fd,filesize($filename));
	fclose($fd);
	$src = ImageCreateFromString($image_string);

	// Calculate new size
	$aspect=imagesx($src)/imagesy($src);
	if(imagesx($src)>$max_x) {
		// Try max width
		$new_x=$max_x;
		$new_y=$new_x/$aspect;
		if($new_y > $max_y) {
			// Use max height instead
			$new_y=$max_y;
			$new_x=$new_y*$aspect;
		}
	} elseif(imagesy($src)>$max_y) {
		$new_y=$max_y;
		$new_x=$new_y*$aspect;
	} else {
		// Image is not wider than $max_x or higher than $max_y
		// Copy entire image
		$new_x=imagesx($src);
		$new_y=imagesx($src);
	}

	// Create destination image object
	$dest = imagecreatetruecolor($new_x, $new_y);

	// Do the copy
	imagecopyresampled($dest, $src, 0, 0, 0, 0, $new_x, $new_y, imagesx($src), imagesy($src));
	return imagejpeg($dest, $dest_fn, $thumb_jpeg_quality);
}

if(isset($_GET['file'])) {
	$filename=basename($_GET['file']);
	if(file_exists($filename)) {
		if(!file_exists($thumb_filename_prefix.$filename)) {
			if(!resize($thumb_size_x, $thumb_size_y, $filename, $thumb_filename_prefix.$filename)) {
				die("Something went wrong, please check that I have write permissions to this directory.");
			}
		}
		
		$image_string=file_get_contents($thumb_filename_prefix.$filename);
		$img=imagecreatefromstring($image_string);

		header("Content-type: image/jpeg");
		imagejpeg($img);

	}
}

?>
